<?php

namespace app\api\admin\v1\service;

use zhanshop\App;

class EchartsService
{
    public function connections(string $date)
    {
        $data = [
            'dates' => [date('Ymd', strtotime('-1 day')),date('Ymd', strtotime('-2 day')),date('Ymd', strtotime('-3 day')),date('Ymd', strtotime('-4 day')),date('Ymd', strtotime('-5 day')),date('Ymd', strtotime('-6 day')),date('Ymd', strtotime('-7 day')),date('Ymd', strtotime('-8 day')),date('Ymd', strtotime('-9 day')),date('Ymd', strtotime('-10 day')),date('Ymd', strtotime('-11 day')),date('Ymd', strtotime('-12 day')),date('Ymd', strtotime('-13 day')),date('Ymd', strtotime('-14 day'))],
            'connections' => [
                'time' => [],
                'value' => [],
                'realtime' => [],
                'realval' => [],
            ],
            'requestip100' => []
        ];

        $statsLog = App::rootPath().'/docker/nginx/stats/connections-'.date('Ymd').'.log';
        if(file_exists($statsLog)){
            $arr = explode("\n", file_get_contents($statsLog));
            foreach ($arr as $k => $v){
                if($v){
                    $rows = explode(',', $v);
                    $data['connections']['realtime'][] = $rows[0];
                    $data['connections']['realval'][] = $rows[1];
                }
            }
        }

        $statsLog = App::rootPath().'/docker/nginx/stats/connections-'.$date.'.log';
        if(file_exists($statsLog)){
            $arr = explode("\n", file_get_contents($statsLog));
            foreach ($arr as $k => $v){
                if($v){
                    $rows = explode(',', $v);
                    $data['connections']['time'][] = $rows[0];
                    $data['connections']['value'][] = $rows[1];
                }
            }
        }

        return $data;
    }

    /**
     * 获取地图
     * @param string $date
     * @return array|mixed
     */
    public function map(string $date){
        if(is_numeric($date)){
            $date = date('Y-m-d', strtotime($date.' day'));
        }
        if($date == false) $date = date('Y-m-d', strtotime('-1 day'));
        $date = str_replace('-', '', $date);
        $statsLog = App::rootPath().'/docker/nginx/stats/stats-'.$date.'.log';
        if(file_exists($statsLog)){
            return json_decode(file_get_contents($statsLog), true);
        }
        return [];
    }
}